package view;

import entity.Order;
import entity.Products;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import services.Service;

import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Font;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class Report2JPanel {
    JPanel backgroundPanel;
    Service service;
    public Report2JPanel(Service service, IndexJFrame indexJFrame) {
        this.service = service;
        backgroundPanel = new JPanel(new BorderLayout());
        initChartPanel();
    }

    private void initChartPanel() {
        Map<String, Order> orderMap = service.getOrderMap();
        Map<String, Products> productsMap = service.getProductMap();
        // 构建数据集合
        Map<String ,Integer> productPriceMap = new HashMap<>();

        for(Order order : orderMap.values()){
            ArrayList<String> productIds = order.getProductsIds();
            for(int i=0;i<productIds.size();i++){
                if(productPriceMap.get(productIds.get(i))==null){
                    productPriceMap.put(productIds.get(i),order.getAmounts().get(i));
                }else {
                    productPriceMap.put(productIds.get(i),productPriceMap.get(productIds.get(i))+order.getAmounts().get(i));
                }
            }
        }
        DefaultPieDataset dataset = new DefaultPieDataset();
        for(Map.Entry<String, Integer> entry : productPriceMap.entrySet()){
            dataset.setValue(productsMap.get(entry.getKey()).getName(),entry.getValue());
        }

        //创建主张图表
        JFreeChart chart =  ChartFactory.createPieChart3D(
                "产品统计报表",//图形的主标题
                dataset, //图形的数据集合
                true,//是否显示子标题
                true,//是否生产数据提示
                true);//是否生产url链接

        //处理主标题乱码

        chart.getTitle().setFont(new Font("宋体",Font.BOLD,15));
        //处理子标题乱码
        chart.getLegend().setItemFont(new Font("宋体",Font.BOLD,15));

        //获取图表区域对象
        /*
         * 三种获取图标对象的方法
         *  1.debug
         *  2.输出（system.out.println()）
         *  3.api文档
         */

        PiePlot3D piePlot3D = (PiePlot3D) chart.getPlot();

        //处理图形上显示的乱码问题
        piePlot3D.setLabelFont(new Font("宋体",Font.BOLD,15));

        //在图形上显示数值
        String labelFormat  = "{0},{1},({2})";
        piePlot3D.setLabelGenerator(new StandardPieSectionLabelGenerator(labelFormat));

        //加载图形
        ChartPanel chartPanel = new ChartPanel(chart);
        backgroundPanel.add(chartPanel);
    }
}
